const { friendshipActivityList } = require('../../../../api/fraternity');
const { formatTime2 } = require('../../../../utils/util');
const { getDict } = require('../../../../utils/dict');

const {
  isFinished
} = require('./tools');

// pages/home/index.js
Page({
  /*** 页面的初始数据 */
  data: {
    id: '',
    page: {
      pageNumber: 1,
      pageSize: 20,
      friendshipAssociationId: '',
      applyStudentId: wx.getStorageSync('studentid'),
      activityStates: ["00", "01"] //  报名中
    },
    total: 0, //  总条数
    finished: false,
    loading: false,
    status: [],
    dataList: [],
    activityStateDicts: [],
    tabs: [
      { name: '报名中', code: ['00', '01'] },
      { name: '进行中', code: ['02', '03'] },
      { name: '已结束', code: ['99'] },
      { name: '审核中', code: ['-1', '0'] }
    ],
    list: [] //  数据列表
  },
  onClick( event ) {
    var page = getCurrentPages();
    //  保存当前的位置，便于后期跳转回来的时候进行其他操作
    const curIndex = page.length - 1;

    const { url } = event.currentTarget.dataset;
    wx.navigateTo({ 
      url,
      success(e) {  //  每次进入 tab页都刷新一下
          const toPage = page[ curIndex ];
          if (toPage == undefined || toPage == null) return;
          wx.setStorageSync('success_back_index', curIndex);
        }
    });
  },
  onRefresh() {
    this.data.page.pageNumber = 1;
    this.data.finished = false;
    this.setData({list: []}, () => {
      fecthList.call(this);
    })
  },
  onJump( event ) { //  页面跳转
    const { url } = event.currentTarget.dataset;
    wx.navigateTo({ url });
  },
  //  切换 tab 发送请求
  onChangeTabs(event) {
    const { code } = event.detail;
    this.data.page.activityStates = code;
    this.setData({ curTab: code }, () => {
      this.data.page.pageNumber = 1;
      this.data.finished = false;
      this.data.list = [];
      this.setData({ list: [] }, () => {
        fecthList.call(this);
      })
    });
  },
  loadMore() {  //  加载更多
    fecthList.call(this);
  },
  async onFace() {
   
  },
  /*** 生命周期函数--监听页面加载 */
  async onLoad(options) {
    this.data.id = options.id;
    this.setData({id: this.data.id });
    const res = await getDict('ACTIVITY_STATE');
    this.setData({ activityStateDicts: res || [] }, () => {
      fecthList.call(this);
    });
  }
})

//  获取列表数据
async function fecthList() {
  fetchFriendshipActivityList.call(this);
}

//  获取当前活动热门活动列表
async function fetchFriendshipActivityList() {
  this.data.page.friendshipAssociationId = this.data.id;
  wx.showLoading({ title: '加载中...' });

  const {
    errors,
    result,
    totalCount
  } = await friendshipActivityList(this.data.page);

  if (errors.lenght > 0) {
    return;
  }

  //  判断数据是不是都已经加载完了
  this.setData({
    finished: isFinished(totalCount, this.data.page.pageNumber * this.data.page.pageSize)
  });
  //  加载更多数据
  this.setData({
    list: this.data.list.concat(setResult.call(this, result))
  });
  this.data.page.pageNumber++;

  wx.hideLoading();
}

function setResult(data = []) {
  const _data = JSON.parse(JSON.stringify(data));

  _data.map(item => {
    item.activityBeginTime = formatTime2( item.activityBeginTime );
    item.activityEndTime = formatTime2( item.activityEndTime );
    item.registrationBeginTime = formatTime2( item.registrationBeginTime );
    item.registrationEndTime = formatTime2( item.registrationEndTime );
    

    if( item.auditFlag === '9' ) {
      item.name = '已驳回';
      item.status = 'status-' + item.auditFlag;
    } else {
      item.name = this.data.activityStateDicts.find(_d => _d.code === item.activityState )?.name;
      item.status = 'status-' + item.activityState;
    }

    return item;
  })

  return _data;
}

//  获取活动状态字典项